<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Cuser;
use Illuminate\Http\Request;
use App\Models\Authorization;
use App\Jobs\SendRegisterEmail;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;

class CuserController extends BaseController
{
    /**
     * @api {get} /users/{id} 某个用户信息(some user's info)
     * @apiDescription 某个用户信息(some user's info)
     * @apiGroup user
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       "data": {
     *         "id": 2,
     *         "email": "490554191@qq.com",
     *         "name": "fff",
     *         "created_at": "2015-11-12 10:37:14",
     *         "updated_at": "2015-11-13 02:26:36",
     *         "deleted_at": null
     *       }
     *     }
     */
    public function show($id)
    {
        $user = Cuser::findOrFail($id);
		$data = $user->attributesToArray();
		\Log::info('user data: '.var_export($data, true));
		return $this->returnSuccess($data);	
    }
	
	/**
	 * http://api.cut.com/api/register?phone=15217331661&code=
	 * @api {post} /register 注册一个用户(create a user)
	 * @apiDescription 注册一个用户(create a user)
	 * @apiGroup user
	 * @apiPermission none
	 * @apiVersion 0.1.0
	 * @apiParam {Phone}  phone   phone[unique]
	 * @apiErrorExample {json} Error-Response:
	 *     HTTP/1.1 400 Bad Request
	 *     {
	 *         "email": [
	 *             "手机已被使用"
	 *         ],
	 *     }
	 */
	public function register(Request $request)
	{
	    $validator = \Validator::make($request->input(), [
	        'phone' => 'required|phone|unique:cut_users',
	        'code' => 'required|string',
	    ]);
	
	    if ($validator->fails()) {
	        return $this->returnError($validator);
	    }
	
	    $code = $request->get('code');
	    $phone = $request->get('phone');
		
		//check code 
		$value = Cache::get('phone_captcha_'.$phone);
		$value = 1234;
		if(empty($value)){
			return $this->returnFail(trans('auth.captcha_retry_again'));
		}
		if($value != $code){
			return $this->returnFail(trans('auth.captcha_noeq'));
		}
		$password = '123456';
	    $attributes = [
			'name' => $phone,
	        'phone' => $phone,
			'password' => app('hash')->make($password),
	    ];
	    $user = User::create($attributes);
	
	    // 201 with location
	    // $location = dingo_route('v1', 'users.show', $user->id);
	
		// {"data":{"id":1,"email":null,"name":"15217331661","headimg":null,"created_at":"2020-08-10 08:45:03","updated_at":"2020-08-10 08:45:03"}}
	    // return $this->response->item($user, new UserTransformer())
	    //     ->header('Location', $location)
	    //     ->setStatusCode(201);
		if(! $token = \Auth::guard('api')->attempt(['phone' => $phone, 'password' => $password])){
			return $this->returnFail(trans('auth.nocorrect_user'));
		}
		
		$authorization = new Authorization($token);
		$authInfo = $authorization->toArray();
		// $userInfo =  $this->response->item($user, new UserTransformer());
		//{"code":0,"msg":"success","data":{"exception":null,"headers":{},"original":{"name":"15217331661","phone":"15217331661","updated_at":"2020-08-11 07:54:33","created_at":"2020-08-11 07:54:33","id":1}}}
		$userInfo = $user->attributesToArray();
		$userInfo['auth_info'] = $authInfo;
		return $this->returnSuccess($userInfo);
	}
	
	/**
	 * 登录
	 * @param {Object} Request $request
	 * 
	 */
	public function login(Request $request)
	{
	    $code = $request->get('code');
	    $phone = $request->get('phone');
	    $country = $request->get('country');
	    $from = $request->get('dx');
	    $pre = $from ? $from .'_' : '';
	    //check code 
	    $value = Cache::get($pre.'phone_captcha_'.$country.'_'.$phone);
	    // $value = 1234;
	    if(empty($value)){
	    	return $this->returnFail(trans('auth.captcha_retry_again'), $code);
	    }
	    if($value != $code){
	    	return $this->returnFail(trans('auth.captcha_noeq'));
	    }
		
		$exists = Cuser::where('phone', $phone)->first();
		$password = '123456';
		if(!$exists){
			
			$attributes = [
				'name' => $phone,
				'phone' => $phone,
				'password' => app('hash')->make($password),
			];
			$user = Cuser::create($attributes);
			if(!$user){
				// return $this->returnFail(trans('auth.nocorrect_user'));
			}
		}
		//tymon/jwt-auth/src/JWTAuth.php 会返回token
		if(! $token = \Auth::guard('api')->attempt(['phone' => $phone, 'password' => $password])){
			// $this->response->errorUnauthorized(trans('auth.incorrect'));
			return $this->returnFail(trans('auth.nocorrect_user'));
		}
		
	    $authorization = new Authorization($token);
		$item = $authorization->toArray();
		
		return $this->returnSuccess($item, trans('auth.correct'));
	}
}
